import { unionBy, remove } from 'lodash-es';
export interface TreeNode {
	value: string;
	label: string;
	children?: TreeNode[] | undefined;
}
export interface Division {
	code: string;
	name: string;
	parent_code: string;
	level: number;
}

export function buildTree(list: Division[]) {
	const tree: TreeNode[] = [];
	const rootList = list.filter((d) => d.level === 1);
	rootList.forEach((r) => {
		const node: TreeNode = {
			label: r.name,
			value: r.code,
		};
		node.children = list.filter((d) => d.parent_code === node.value).map((r) => ({ value: r.code, label: r.name }));
		tree.push(node);
	});
	return tree;
}

export function getRegionNames(list: Division[], regions: string[][]) {
	const regionList: string[] = [];
	regions.forEach((c: string[]) => {
		const names: string[] = [];
		c.forEach((cr) => {
			const d = list.find((d) => d.code == cr);
			if (d) {
				names.push(d.name);
			}
		});
		regionList.push(names.join('/'));
	});
	return regionList.join(',');
}

export function filterRegion(list: Division[], regions: string[][]) {
	let regionList: Division[] = [];
	regions.forEach((c: string[]) => {
		if (c.length === 0) return;
		if (c.length === 1) {
			const t: Division[] = list.filter((d) => d.code == c[0] || d.parent_code == c[0]);
			regionList = [...regionList, ...t];
		}
		if (c.length > 1) {
			const t: Division[] = list.filter((d) => c.includes(d.code));
			regionList = [...regionList, ...t];
		}
	});
	console.log(regionList);
	console.log(unionBy(regionList, 'code'));
	return unionBy(regionList, 'code');
}

/**
 * 将地区字符串转换为json
 * 处理级联选择 ，比如 [['12'],['12','1213']] 要把独立的 ['12'] 删掉， 表明选了单独是下级就不能选上级
 * @param region
 * @returns
 */
export function parseRegionToJson(region: string) {
	if (region) {
		const regionArr: string[][] = JSON.parse(region);
		const levelOne = regionArr.filter((r: string[]) => r.length === 1);
		const levelTwo = regionArr.filter((r: string[]) => r.length > 1);
		levelOne.forEach((r: string[]) => {
			const index = levelTwo.findIndex((l: string[]) => l.includes(r[0]));
			if (index !== -1) {
				remove(regionArr, (s: string[]) => s.length === 1 && s[0] === r[0]);
			}
		});
		return regionArr;
	}
	return []
}
